package com.fwtai.service.api;

import com.fwtai.api.ApiKnowledgeDao;
import com.fwtai.bean.PageFormData;
import com.fwtai.config.ConfigFile;
import com.fwtai.config.LocalUserId;
import com.fwtai.service.AsyncService;
import com.fwtai.tool.ToolClient;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 收藏知识
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2021年7月22日 11:43:17
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class ApiKnowledgeService{

  private final ApiKnowledgeDao apiKnowledgeDao;

  private final AsyncService asyncService;

  private final ThreadPoolTaskExecutor taskExecutor;

  public ApiKnowledgeService(final ApiKnowledgeDao apiKnowledgeDao,final AsyncService asyncService,final ThreadPoolTaskExecutor taskExecutor){
    this.apiKnowledgeDao = apiKnowledgeDao;
    this.asyncService = asyncService;
    this.taskExecutor = taskExecutor;
  }

  public String listDataPage(final HttpServletRequest request){
    final PageFormData formData = ToolClient.pageParamsApi(request);
    if(formData == null) return ToolClient.jsonValidateField();
    final CompletableFuture<List<Map<String,Object>>> asyncListData = CompletableFuture.supplyAsync(() -> apiKnowledgeDao.listData(formData),taskExecutor);
    return ToolClient.jsonPage(asyncListData.join());
  }

  public String getInfo(final String kid){
    if(kid == null || kid.length() <=0){
      return ToolClient.jsonValidateField();
    }
    final String query = apiKnowledgeDao.queryExist(kid);
    if(query == null){
      return ToolClient.createJsonFail("内容已被删除");
    }
    final String loginId = LocalUserId.get();
    final HashMap<String,String> params = new HashMap<>(2);
    if(loginId != null){
      params.put("loginId",loginId);
    }
    params.put("kid",kid);
    final HashMap<String,Object> info = apiKnowledgeDao.getInfo(params);
    asyncService.updateBrowse(kid);
    return ToolClient.queryJson(info);
  }

  public String listSearchData(final HttpServletRequest request){
    final PageFormData formData = ToolClient.pageParamsApi(request);
    if(formData == null) return ToolClient.jsonValidateField();
    formData.put("loginId",LocalUserId.get());
    final HashMap<String,Object> map = apiKnowledgeDao.listSearchData(formData);
    return ToolClient.jsonPage((List<?>) map.get(ConfigFile.rows));
  }
}